<template>
  <div class="flex flex-wrap relative justify-center">
    <input
      ref="inputRef"
      class="code-input z-10 h-full w-full opacity-0 select-none absolute outline-0"
      :maxlength="maxLen"
      @keydown.left.tab="
        (e) => {
          e.preventDefault()
        }
      "
      v-model="bindValue"
    />
    <slot
      v-for="(v, i) in nowLen ? bindValue.split('').concat(new Array(maxLen - nowLen)) : ' '.repeat(maxLen)"
      :key="`input${i}`"
      :filled="v && nowLen"
      :next="i === nowLen"
      :over="nowLen === maxLen"
      :focused="focused"
    >
      <span
        :class="[
          {
            __next: focused && i === nowLen,
            __full: focused && i + 1 === maxLen && nowLen === maxLen,
          },
          'select-none inline-block text-lg h-6 w-6 mx-1 outline-none text-center p-0',
          'flex items-center justify-center border ',
        ]"
      >
        {{ v ? (nowLen ? '●' : '') : '' }}
      </span>
    </slot>
  </div>
</template>

<script setup lang="ts">
const props = withDefaults(defineProps<{ modelValue: string; maxLen: number }>(), { maxLen: 6 })
const emits = defineEmits(['update:modelValue'])

const bindValue = useVModel(props, 'modelValue', emits)
const nowLen = computed(() => bindValue.value.length)

const inputRef = ref()
const { focused } = useFocus(inputRef)

watch(
  () => nowLen.value,
  (len) => {
    if (len === props.maxLen) console.log('!')
  },
)
</script>

<style scoped lang="scss">
.__next {
  @apply ring-1;
  &::after {
    content: 'I';
    font-family: Cambria;
    animation: fade-in 0.5s ease-in-out infinite alternate;
    @apply text-base;
  }
}
.__full {
  @apply ring-1;
}
</style>
